/*
 * TmtCategory.h
 * ----------------
 * TmtCategory - extending the built-in NSData, NSString, and NSDictionary classes with methods that make them more useful for interacting with the Tmt web services.
 *
 * Author: Chris Lee <clee@mg8.org>
 * License: GPL v2 <http://www.opensource.org/licenses/gpl-license.php>
 */
#import "TmtCategory.h"

@implementation NSData (Tmt)
- (NSString *)md5HexHash
{
	unsigned char digest[16];
	char finalDigest[32];


	MD5([self bytes], [self length], digest);
	unsigned short int i;
	for (i = 0; i < 16; i++)
		sprintf(finalDigest + (i * 2), "%02x", digest[i]);

	return [NSString stringWithCString: finalDigest length: 32];
}
@end

@implementation NSString (Tmt)
- (NSString *)md5HexHash
{
	NSLog(@"-------\n==String to hash: %@\n---------", self);
	return [[self dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion: NO] md5HexHash];
}

- (NSString *)URLEncode
{
   CFStringRef decodedString = (CFStringRef)self;
   CFStringRef recodedString = CFURLCreateStringByAddingPercentEscapes
	   (kCFAllocatorDefault, decodedString, NULL, @"+()`#%^[]{}\\|\"<>\/", kCFStringEncodingUTF8);
   NSString* answer = (recodedString != NULL) ? [(NSString*)
	   recodedString autorelease] : self ;
   return answer ;
}
@end

@implementation NSDictionary (Tmt)
- (NSArray *)pairsJoinedByString: (NSString *)j encoded: (BOOL) encoded
{
	NSArray *sortedKeys = [[self allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
	NSMutableArray *allKeysAndObjects = [NSMutableArray array];
	unsigned int i;
	for (i = 0; i < [sortedKeys count]; i++) {
		NSString *key = [sortedKeys objectAtIndex: i];
		
		NSString *val = nil;
	    if( encoded ) {
			val = [[self objectForKey: key] URLEncode];
		} else {
			val = [self objectForKey: key];
		}

		[allKeysAndObjects addObject: [NSString stringWithFormat: @"%@%@%@", key, j, val]];
	}


	return [NSArray arrayWithArray: allKeysAndObjects];
}
@end

